class WordDefinition < ActiveRecord::Base

	belongs_to :word  
	belongs_to :dictionary

  validates_associated :word, :dictionary

  def self.per_page
    1
  end

  # Available options so far:
  # page -> requested will_paginate page number
  # limit -> will limit the result count from the query to the db
  # force_look_up -> if true, will force an online dictionaries look up
  def self.for(word, dictionary = nil, options = {})
    if options[:force_look_up]
      if dictionary
        DictServiceHelper.define_in_dictionary(word, dictionary)
      else
        DictServiceHelper.define(word)
      end
    end

    WordDefinition.for_word_and_dictionary(word, dictionary, options)
  end

  private

  def self.for_word_and_dictionary(word, dictionary = nil, options = {})
    conditions = ['word_id = :word_id']
    conditions_hash = {:word_id => word.id}

    if dictionary
      conditions << 'dictionary_id = :dictionary_id'
      conditions_hash.merge! :dictionary_id => dictionary.id
    end

    self.paginate(:page => options[:page],
                  :per_page => options[:limit],
                  :conditions => [conditions.join(' AND '), conditions_hash],
                  :order => 'position')
  end
end
